//
//  UndertheFrame.m
//  微他
//
//  Created by 微他 on 14-7-17.
//  Copyright (c) 2014年 微他. All rights reserved.
//

#import "UndertheFrame.h"
#import "SRAccountNetService.h"
#import "UIImage+Ex.h"

@interface UndertheFrame ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSArray *_arr;
}
@end

@implementation UndertheFrame

- (id)initWithFrame:(CGRect)frame isSex:(BOOL)isSex
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        if (isSex) {
            _arr = @[@"男",@"女",@"取消"];
        }else
            _arr = @[@"拍照",@"从相册选择",@"取消"];
        [self initInterface];
    }
    return self;
}

- (void)initInterface
{
    self.backgroundColor = [UIColor clearColor];
    _black = [[UIView alloc] initWithFrame:self.frame];
    _black.backgroundColor = [UIColor blackColor];
    _black.alpha = 0.6;
    _black.tag = 699;
    [self addSubview:_black];
    
    UIView *spaceView = [[UIView alloc] initWithFrame:CGRectMake(10, CGRectGetHeight(self.bounds) - 180, CGRectGetWidth(_black.bounds) - 20, 100)];
    spaceView.backgroundColor = [UIColor whiteColor];
    spaceView.tag = 700;
    spaceView.layer.cornerRadius = 6;
    [self addSubview:spaceView];
    
    self.clipsToBounds = YES;
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 setTitle:_arr[0] forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 0, CGRectGetWidth(spaceView.frame), 50);
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [spaceView addSubview:button1];
    
    UIView *xian = [[UIView alloc] initWithFrame:CGRectMake(0, 50, CGRectGetWidth(spaceView.frame), 0.5)];
    xian.backgroundColor = [UIColor lightGrayColor];
    [spaceView addSubview:xian];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button2 setTitle:_arr[1] forState:UIControlStateNormal];
    button2.frame = CGRectMake(0, 50, CGRectGetWidth(spaceView.frame), 50);
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [spaceView addSubview:button2];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button3 setTitle:_arr[2] forState:UIControlStateNormal];
    button3.frame = CGRectMake(10, CGRectGetMaxY(spaceView.frame) + 10, CGRectGetWidth(spaceView.frame), 50);
    [button3 setTitleColor:[UIColor colorWithRed:144.0/255.0 green:87.0/255.0 blue:192.0/255.0 alpha:1] forState:UIControlStateNormal];
    button3.backgroundColor = [UIColor whiteColor];
    button3.layer.cornerRadius = 6;
    [button3.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [button3 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button3];
}

- (void)buttonClick:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"男"] || [sender.titleLabel.text isEqualToString:@"女"]) {
        [_delegate undertheStr:sender.titleLabel.text];
        [self removeFromSuperview];
        return;
    }
    UIImagePickerController * mipc = [[UIImagePickerController alloc] init];
    if ([sender.titleLabel.text isEqualToString:@"拍照"]) {
        mipc.allowsEditing = YES;//是否可编辑照片
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            NSLog(@"设备不支持访问照相机");
            return;
            
        }
        mipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
    }else if ([sender.titleLabel.text isEqualToString:@"从相册选择"]) {
        mipc.allowsEditing = YES;//是否可编辑照片
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            NSLog(@"设备不支持访问相册");
            
            return;
        }
        mipc.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }else if ([sender.titleLabel.text isEqualToString:@"取消"]) {
        UIView *view = (UIView *)[self viewWithTag:700];
        UIView *tempview = (UIView *)[self viewWithTag:699];
        [UIView animateWithDuration:0.3 animations:^{
//            view.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(view.bounds), 215);
            tempview.alpha = 0;
            view.alpha = 0;
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
            }
        }];
        return;
    }
    mipc.delegate = self;//委托
    
    mipc.mediaTypes=[NSArray arrayWithObjects:@"public.movie",@"public.image",nil];
    [[self viewController] presentViewController:mipc animated:YES completion:^{
        
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch.view.tag != 700) {
        UIView *view = (UIView *)[self viewWithTag:700];
        UIView *tempview = (UIView *)[self viewWithTag:699];
        //        [UIView animateWithDuration:0.2 animations:^{
        //            view.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(view.bounds), 215);
        //            tempview.alpha = 0;
        //        } completion:^(BOOL finished) {
        [self removeFromSuperview];
        //        }];
        return;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage] == nil?info [UIImagePickerControllerOriginalImage]:info[UIImagePickerControllerEditedImage];
    UIImage *scaledImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(160, 160)];
    [_delegate undertheFrame:scaledImage];
    [SVProgressHUD show];
    [[SRAccountNetService modifyUserHeadImg:[scaledImage data]]
     subscribeNext:^(id x) {
         [SVProgressHUD dismiss];
     }];
    UIViewController *controller = [self viewController];
    UIView *view = (UIView *)[self viewWithTag:700];
    view.alpha = 0;
    [view removeFromSuperview];
    [self removeFromSuperview];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [controller dismissViewControllerAnimated:YES completion:NULL];
    
}

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[self viewController] dismissViewControllerAnimated:YES completion:NULL];
}

- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next =
         next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController
                                          class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
